package net.lwf.hibernate.dao;


import java.util.List;


import net.lwf.exception.ExceptionUtil;
import net.lwf.hibernate.entity.User;
import net.lwf.hibernate.util.HibernateUtil;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Expression;


public class UserDAO extends BaseDAO {
	
	@SuppressWarnings("unchecked")
	public User getUser(String userid) {
	    Session session = HibernateUtil.getSessionFactory().openSession();
	    try {
	    	Criteria criteria = session.createCriteria(User.class);
	    	criteria.add(Expression.eq("userId", userid));
	    	List<User> users = criteria.list();
	    	if(users != null && users.size() != 0) {
	    		return (User) users.get(0);	
	    	}
	    	
	    }
	    catch(HibernateException hex) {
	    	ExceptionUtil.logAndThrowException(UserDAO.class, hex);
	    }
	    finally {
	    	if(session != null) {
	    		session.close();
	    	}
	    }
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public List<User> getAllUsers() {
		List data = null;
	    Session session = HibernateUtil.getSessionFactory().openSession();
	    try {
	    	Criteria criteria = session.createCriteria(User.class);
	    	data = criteria.list();	
	    }
	    catch(HibernateException hex) {
	    	ExceptionUtil.logAndThrowException(UserDAO.class, hex);
	    }
	    finally {
	    	if(session != null) {
	    		session.close();
	    	}
	    }
		return data;
		
	}
	
	public void saveUser(User user) {
	    Transaction tx = null;
	    Session session = HibernateUtil.getSessionFactory().openSession();
	    try {
	      tx = session.beginTransaction();
	      if(user.getId() == 0) {
	    	  session.save(user);  
	      }
	      else {
	    	  session.update(user);
	      }
	      tx.commit();
	    }
	    catch(HibernateException hex) {
	    	ExceptionUtil.logAndThrowException(UserDAO.class, hex);
	    }
	    finally {
	    	if(session != null) {
	    		session.close();
	    	}
	    }
	}

}
